<template>
  <div class="apartment-allocation">
    <el-row :gutter="20">
      <el-col :span="12">
        <div class="tenant-section">
          <el-form :inline="true" :model="tenantQuery">
            <el-form-item label="省">
              <el-select
                @change="getCities(tenantQuery.province)"
                v-model="tenantQuery.province"
                placeholder="请选择省"
              >
                <el-option
                  v-for="item in provinces"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="市">
              <el-select
                @change="getAreas(tenantQuery.province,tenantQuery.city)"
                v-model="tenantQuery.city"
                placeholder="请选择市"
              >
                <el-option
                  v-for="item in cities"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="区域">
              <el-select v-model="tenantQuery.requestedArea" placeholder="请选择区域">
                <el-option
                  v-for="item in areas"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="状态">
              <el-select v-model="tenantQuery.status" placeholder="请选择状态">
                <el-option
                  v-for="item in status"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="姓名">
              <el-input v-model="tenantQuery.name" placeholder="请输入姓名"></el-input>
            </el-form-item>
            <el-form-item label="人数">
              <el-select v-model="tenantQuery.familySize" placeholder="请选择人数">
                <el-option
                  v-for="item in peopleCounts"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="searchTenants">查询</el-button>
              <el-button @click="clearTenants">全部清除</el-button>
              <el-button type="success" @click="batchAssign">批量分配</el-button>
              <el-button type="info" @click="batchSave">保存分配</el-button>
            </el-form-item>
          </el-form>
          <el-table :data="tenants" style="width: 100%">
            <el-table-column label="选择">
              <template slot-scope="scope">
                <el-radio class="radio" v-model="templateSelection" :label="scope.row">&nbsp;</el-radio>
              </template>
            </el-table-column>
            <el-table-column prop="realName" label="姓名"></el-table-column>
            <el-table-column prop="requestedArea" label="区域"></el-table-column>
            <el-table-column prop="familySize" label="家庭人数"></el-table-column>
            <el-table-column prop="assignedApartment" label="分配的住房"></el-table-column>
            <el-table-column label="操作" width="120px">
              <template slot-scope="scope">
                <el-button @click="clearAssignment(scope.row)">清除分配</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            v-if="tenants.length > 0"
            @size-change="tenantHandleSizeChange"
            @current-change="tenantHandleCurrentChange"
            :current-page="tenantCurrentPage"
            :page-size="tenantPageSize"
            layout="total, prev, pager, next, jumper"
            :total="tenantTotal"
          ></el-pagination>
        </div>
      </el-col>
      <el-col :span="12">
        <div class="apartment-section">
          <el-form :inline="true" :model="apartmentQuery">
            <el-form-item label="省">
              <el-select
                @change="getCities(apartmentQuery.province)"
                v-model="apartmentQuery.province"
                placeholder="请选择省"
              >
                <el-option
                  v-for="item in provinces"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="市">
              <el-select
                @change="getAreas(apartmentQuery.province,apartmentQuery.city)"
                v-model="apartmentQuery.city"
                placeholder="请选择市"
              >
                <el-option
                  v-for="item in cities"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="区域">
              <el-select
                @change="getCommunities(apartmentQuery.areaName)"
                v-model="apartmentQuery.areaName"
                placeholder="请选择区域"
              >
                <el-option
                  v-for="item in areas"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="小区">
              <el-select v-model="apartmentQuery.community" placeholder="请选择小区">
                <el-option
                  v-for="item in communities"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="面积">
              <el-input v-model="apartmentQuery.areaMin" style="width:100px" placeholder="最小面积"></el-input>
              <span>&thinsp;到&thinsp;</span>
              <el-input v-model="apartmentQuery.areaMax" style="width:100px" placeholder="最大面积"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="searchApartments">查询</el-button>
            </el-form-item>
          </el-form>
          <el-table :data="apartments" style="width: 100%">
            <el-table-column prop="index" label="序号" width="55px"></el-table-column>
            <el-table-column prop="roomNumber" label="套房号" width="80px"></el-table-column>
            <el-table-column prop="area" label="面积" width="60px"></el-table-column>
            <el-table-column prop="areaName" label="区域" width="80px"></el-table-column>
            <el-table-column prop="image" label="图片" width="70px">
              <template slot-scope="scope">
                <img
                  :src="scope.row.image"
                  alt="apartment image"
                  style="width: 50px; height: 50px;"
                />
              </template>
            </el-table-column>
            <el-table-column prop="layout" label="户型"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button @click="assignApartment(scope.row)">分配</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            v-if="apartments.length > 0"
            @size-change="apartmentHandleSizeChange"
            @current-change="apartmentHandleCurrentChange"
            :current-page="apartmentCurrentPage"
            :page-size="apartmentPageSize"
            layout="total, prev, pager, next, jumper"
            :total="apartmentTotal"
          ></el-pagination>
        </div>
      </el-col>
    </el-row>
  </div>
</template>
  
<script>
export default {
  data() {
    return {
      tenantQuery: {
        province: "",
        city: "",
        requestedArea: "",
        status: "",
        realName: "",
        familySize: ""
      },
      tenants: [],
      tenantCurrentPage: 1,
      tenantPageSize: 3,
      tenantTotal: "",
      apartmentQuery: {
        province: "",
        city: "",
        areaName: "",
        community: "",
        areaMin: "",
        areaMax: ""
      },
      apartments: [],
      apartmentCurrentPage: 1,
      apartmentPageSize: 3,
      apartmentTotal: "",
      provinces: [],
      cities: [],
      areas: [],
      communities: [],
      status: [
        { label: "已分配", value: "已分配" },
        { label: "未分配", value: "已审核" }
      ],
      peopleCounts: [
        { label: "1人", value: "1" },
        { label: "2人", value: "2" },
        { label: "3人", value: "3" },
        { label: "4人", value: "4" },
        { label: "5人", value: "5" },
        { label: "6人", value: "6" }
      ],
      templateSelection: null
    };
  },
  mounted() {
    this.getProvinces();
    this.searchApartments();
    this.searchTenants();
    this.$nextTick(() => {
      const radios = this.$el.querySelectorAll(".el-radio__original");
      radios.forEach(radio => {
        radio.removeAttribute("aria-hidden");
      });
    });
  },
  methods: {
    getProvinces() {
      this.$axios.post("area/province", { none: "none" }).then(res => {
        if (res.data.code === 200) {
          this.provinces = [];
          res.data.data.forEach(province => {
            this.provinces.push({ value: province.name, label: province.name });
          });
        } else {
          this.$message.error(res.data.message);
        }
      });
    },
    getCities(province) {
      this.$axios.post("area/city", { province }).then(res => {
        if (res.data.code === 200) {
          this.cities = [];
          res.data.data.forEach(city => {
            this.cities.push({ value: city.name, label: city.name });
          });
        } else {
          this.$message.error(res.data.message);
        }
      });
    },
    getAreas(province, city) {
      this.$axios
        .post("area/query", {
          province,
          city,
          name: ""
        })
        .then(res => {
          if (res.data.code === 200) {
            this.areas = [];
            res.data.data.forEach(area => {
              this.areas.push({ value: area.name, label: area.name });
            });
          } else {
            this.$message.error(res.data.message);
          }
        });
    },
    getCommunities(area) {
      this.$axios
        .post("community/get", {
          area,
          name: ""
        })
        .then(res => {
          if (res.data.code === 200) {
            this.communities = [];
            res.data.data.forEach(community => {
              this.communities.push({
                value: community.name,
                label: community.name
              });
            });
          } else {
            this.$message.error(res.data.message);
          }
        });
    },
    tenantHandleSizeChange(size) {
      this.tenantPageSize = size;
      this.searchTenants();
    },
    tenantHandleCurrentChange(page) {
      this.tenantCurrentPage = page;
      this.searchTenants();
    },
    searchTenants() {
      this.$axios
        .post("audit/get", {
          ...this.tenantQuery,
          size: this.tenantPageSize,
          curr: (this.tenantCurrentPage - 1) * this.tenantPageSize
        })
        .then(res => {
          if (res.data.code === 200) {
            this.tenants = res.data.data;
            this.tenantTotal = res.data.total;
          } else {
            this.$message.error(res.data.message);
          }
        })
        .catch(err => {
          this.$message.error(err.message);
        });
    },
    clearTenants() {
      if (this.tenants.length === 0) {
        this.$message.warning("没有租客的分配可以清除");
        return;
      }
      this.$confirm("确定清除所有分配吗，已经保存的分配不会被清除", "提示", {
        type: "warning"
      })
        .then(() => {
          this.tenants.forEach(tenant => {
            if (tenant.status !== "已分配") {
              tenant.allocated = false;
              tenant.assignedApartment = null;
            }
          });
          this.apartments.forEach(apartment => {
            if (apartment.status !== "已分配")
              apartment.status.allocated = false;
          });
          this.message.success("租客分配已清除");
        })
        .catch(() => {});
      this.$confirm("确定清除所有分配吗，已经保存的分配不会被清除", "提示", {
        type: "warning"
      })
        .then(() => {
          this.tenants.forEach(tenant => {
            if (tenant.status !== "已分配") {
              tenant.allocated = false;
              tenant.assignedApartment = null;
            }
          });
          this.apartments.forEach(apartment => {
            if (apartment.status !== "已分配")
              apartment.status.allocated = false;
          });
          this.message.success("租客分配已清除");
        })
        .catch(() => {});
    },
    batchAssign() {
      if (this.tenants.length === 0) {
        this.$message.warning("没有租客可以分配");
        return;
      }
      let allocatedTenants = [];
      this.tenants.forEach(tenant => {
        if (tenant.status !== "已分配") allocatedTenants.push(tenant);
      });
      if (allocatedTenants.length === 0) {
        this.$message.error("没有租客可以分配");
        return;
      }
      if (allocatedTenants.length < this.tenants.length)
        this.$message.warning("有租客的分配已经保存，将自动跳过");
      this.$confirm("确定批量随机分配吗，系统分配完毕将自动保存", "提示", {
        type: "warning"
      }).then(() => {
        this.$axios
          .post("audit/allocateBatch", allocatedTenants)
          .then(res => {
            if (res.data.code === 200) {
              this.$message.success("批量分配成功");
              this.searchApartments;
              this.searchTenants;
            } else {
              this.$message.error(res.data.message);
            }
          })
          .catch(err => {
            this.$message.error(err.message);
          });
      });
    },
    batchSave() {
      let allocatedTenants = [];
      this.tenants.forEach(tenant => {
        if (tenant.status !== "已分配") allocatedTenants.push(tenant);
      });
      if (allocatedTenants.length === 0) {
        this.$message.error("没有可保存的分配");
        return;
      }
      if (allocatedTenants.length < this.tenants.length)
        this.$message.warning("有租客的分配已经保存，将自动跳过");
      this.$confirm("确定保存分配吗，保存后将无法清除分配", "提示", {
        type: "warning"
      }).then(() => {
        const params = {
          tenantInfo: allocatedTenants,
          apartment: this.apartments
        };
        this.$axios
          .post("audit/allocateSave", params)
          .then(res => {
            if (res.data.code === 200) {
              this.$message.success("全部保存成功");
              this.searchApartments;
              this.searchTenants;
            } else {
              this.$message.error(res.data.message);
            }
          })
          .catch(err => {
            this.$message.error(err.message);
          });
      }).catch(() => {});
    },
    clearAssignment(row) {
      if (row.status === "已分配") {
        this.$message.error("当前租客分配已保存，不可清除分配！");
        return;
      }
      if (row.allocated) {
        this.$confirm(`确定清除租客${row.realName}的分配吗？`, "提示", {
          type: "warning"
        })
          .then(() => {
            const apartment = this.apartments.find(
              apartment => apartment.roomNumber === row.assignedApartment
            );
            row.allocated = false;
            row.assignedApartment = null;
            if (apartment) {
              apartment.allocated = false;
            }
            this.$message.success("分配已清除");
          })
          .catch(() => {});
      }
      if (row.status === "已分配") {
        this.$message.error("当前租客分配已保存，不可清除分配！");
        return;
      }
      if (row.allocated) {
        this.$confirm(`确定清除租客${row.realName}的分配吗？`, "提示", {
          type: "warning"
        })
          .then(() => {
            const apartment = this.apartments.find(
              apartment => apartment.roomNumber === row.assignedApartment
            );
            row.allocated = false;
            row.assignedApartment = null;
            if (apartment) {
              apartment.allocated = false;
            }
            this.$message.success("分配已清除");
          })
          .catch(() => {});
      }
    },
    apartmentHandleSizeChange(size) {
      this.apartmentPageSize = size;
      this.searchApartments();
    },
    apartmentHandleCurrentChange(page) {
      this.apartmentCurrentPage = page;
      this.searchApartments();
    },
    searchApartments() {
      this.$axios
        .post("apartment/query", {
          ...this.apartmentQuery,
          status: "已发布",
          size: this.apartmentPageSize,
          curr: (this.apartmentCurrentPage - 1) * this.apartmentPageSize
        })
        .then(res => {
          if (res.data.code === 200) {
            this.apartments = res.data.data.map((apartment, index) => {
              return {
                index: index + 1,
                ...apartment,
                layout: `${apartment.rooms}房${apartment.livingRooms}厅${apartment.bathrooms}卫${apartment.balconies}阳`
              };
            });
            this.apartmentTotal = res.data.total;
          } else {
            this.$message.error(res.data.message);
          }
        })
        .catch(err => {
          this.$message.error(err.message);
        });
    },
    assignApartment(row) {
      if (this.templateSelection === null) {
        this.$message.error("请先选择租客");
        return;
      }
      if (this.templateSelection.status === "已分配") {
        this.$message.error("当前租客分配已保存，不可重新分配！");
        return;
      }
      this.$confirm(
        `确定分配${row.roomNumber}号房间给${this.templateSelection.realName}吗？`,
        "提示",
        {
          type: "warning"
        }
      ).then(() => {
        const params = {
          tenantInfo: this.templateSelection,
          apartment: row
        };
        this.$axios
          .post("audit/allocate", params)
          .then(res => {
            if (res.data.code === 200) {
              this.$message.success("分配校验通过！若分配完毕，请点击保存");
              this.tenants[
                this.tenants.indexOf(this.templateSelection)
              ].assignedApartment = row.roomNumber;
              this.tenants[
                this.tenants.indexOf(this.templateSelection)
              ].allocated = true;
              this.apartments[row.index - 1].allocated = true;
              this.templateSelection = {};
            } else {
              this.$message.error(res.data.message);
            }
          })
          .catch(err => {
            this.$message.error(err.message);
          });
      });
    }
  }
};
</script>
  
  <style scoped>
.apartment-allocation {
  padding: 20px;
}
.tenant-section,
.apartment-section {
  border: 1px solid #ebeef5;
  padding: 20px;
  border-radius: 4px;
}
.tenant-section,
.apartment-section {
  height: 80vh;
}
</style>
  